if (!exists("app_root")) {
  stop("Need to have app_root defined to source this template");
}

source ( paste ( app_root, "cgi-lib/R/ep.io.R", sep="/" ) );
source ( paste ( app_root, "cgi-lib/R/bga_ord.R", sep="/" ) );

ep.run_ord <- function ( src, rownam, colnam, filename, outputdir, nf, ordtype, outputlist ) {

  outbase=paste(outputdir,"/",filename,sep="");

##################
# READ DATA
#################

# NOTE a feature of ep.readBin is that it transposes the data!!!
# so I will remove the call to tranpose the data.
# NB:::: if ep.readBin is fixed, bga_ord.R::tranpose is required.

  dataset <- ep.readBin(src);


#########################
# Run Ordination
########################

# In the library made4, the ord type is expected in lowercase. In EP its given in 
# upper case. 

  otype= tolower(ordtype);
  coa.results<-ord(dataset, type=otype, ord.nf=as.real(nf));

####################################
## Produce output summary (log file)
#####################################
  sink(paste(outbase, "_log.txt", sep=""));print(coa.results);sink();


####################################
## Output files
####################################
  outputlist <-strsplit(outputlist, "")[[1]];

#sink(paste(outbase, "_outputlist.txt", sep=""));print(outputlist);sink()

#----------------------------------------------------------------------------
# Write File, Eigenvalues, Column (array) and Row (lines, genes) Co-ordinates
#----------------------------------------------------------------------------

  write.res<-function(outdata="eig", fileExt="_eig.txt") {
    filenam<-  paste(outbase, fileExt, sep = "" );
    data <- signif(coa.results$ord[[outdata]],3);

    # if data has more than 300 rows only retain first 100 and last 100
    if ( 1==0 && is.data.frame ( data ) && nrow ( data ) > 300 ) {
      p <- nrow(data) - 100;
      data <- data[-101:-p,];
    }
    write.table(data,sep="\t",quote=F,row.names = TRUE,col.names = FALSE,file = filenam);
  }

#-------------------------------------------------
## Define plot
#------------------------------------------------
  plot.res <-function(ord, fileExt="_array.png", type="A"){
    filenam<-  paste(outbase, fileExt, sep = "" );
    png(filenam, bg="transparent");
    if (type=="A") plotarrays(ord);
    if (type=="G") plotgenes(ord);
    if (type=="E") scatterutil.eigen(ord$ord$eig); 
    if (type== "B") plot(ord);
    dev.off();
  }

  write.pdb<-function(ord, fileExt="_li", coord="li"){
    filenam<-  paste(outbase, fileExt, sep = "" );
    html3D(ord$ord[[coord]], classvec =NULL, writepdb =TRUE, scaled= TRUE, filenamebase = filenam);
  }

  write.pdb(coa.results);


#-----------------------------------------------
# Parse output wish list
#-------------------------------------------------

  for (i in outputlist) 
    switch(EXPR=i,
## Output txt files from coa.results$ord[4],[9],[10] 
## are $eig (E), array $co (R) and gene $li (C) co-ordinate
	O = print("no files"),
	E = write.res(outdata="eig", fileExt="_eig.txt"),
	C = write.res(outdata="co", fileExt="_co.txt"),
	R = write.res(outdata="li", fileExt="_li.txt"),

## Output images and graphs of genes or arrays
	A = plot.res(ord=coa.results, fileExt="_array.png", type="A"), 		
	G = plot.res(ord=coa.results, fileExt="_genes.png", type="G"),

## Do biplot, To gene plot, add arrays	
	B = plot.res(ord=coa.results, fileExt="_biplot.png", type="B"),

## Eigenvalues
	V = plot.res(ord=coa.results,fileExt="_eig.png", type="E"),
	);

  print(paste("Graphs and output files in ", outputdir, "/", filename, sep=""));
}
